<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2019/11/7
 * Time: 9:31
 */

namespace app\adminapiv3\service\platform_manage;


use app\adminapiv3\service\BaseService;
use app\adminapiv3\service\Upload;
use app\common\model\FilePathModel;
use app\common\service\HostLink;

class ServerUpdateService extends BaseService
{
    /**
     * @name 判断是否更新
     * @return bool
     * @author wx
     * @date 2019/11/7 11:22
     */
    public function isUpdate()
    {
        $filePathModel = new FilePathModel();
        $updateLock = $filePathModel->update_lock;
        if (file_exists($updateLock)) {

            return true;
        }else{

            return false;
        }
    }

    /**
     * @name 产品升级
     * @author wx
     * @date 2019/11/7 11:24
     */
    public function upgrade($url)
    {
        //查找所有的主机
        $hostLink = new HostLink();
        $hostId = $hostLink->findAllHostId();
        return $hostId;
    }


    /**
     * @name 离线更新
     * @param $file
     * @return bool
     * @author wx
     * @date 2019/11/7 11:25
     */
    public function offline($file)
    {
        //记录操作日志
        global $logArray;
        $logArray = array(
            'content' => '产品更新',
        );

        //1. 验证是否正在更新
        if ($this->isUpdate()) {
            $this->setError($this->CODE_SUCCESS,'系统正在更新，请稍后...');
            return false;
        }
        //2. 验证传入文件
        if(!$file){
            $this->setError($this->CODE_FAIL, '请上传更新文件!');
            return false;
        }

        //3. 上传更新包
        $filePath = 'static/ServerUpdate/offline/uploads';
        if (!file_exists($filePath)) {
            mkdir($filePath,0777,true);
        }
        $uploadServer = new Upload();
        $uploadRes = $uploadServer->upload($file, $filePath, 'gz', 512*1024*1024);

        if($uploadRes['code'] != 0){
            $this->setError($this->CODE_FAIL, $uploadRes['msg']);
            return false;
        }

        //4. 获取更新包路径
        $packagePath = $_SERVER['DOCUMENT_ROOT']. '/' . $uploadRes['path'] . $uploadRes['file_name'];

        $filePathModel = new FilePathModel();

        //5. 生成更新文件
        file_put_contents($filePathModel->offline_lock, $packagePath);

        //6. 生成正在更新文件
        $updateLock = $filePathModel->update_lock;
        file_put_contents($updateLock, $packagePath);

        return true;
    }
}